package org.rapla.mobile.android.utility;

import org.apache.avalon.framework.logger.ConsoleLogger;
import org.rapla.RaplaMainContainer;
import org.rapla.facade.ClientFacade;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.StartupEnvironment;
import org.rapla.mobile.android.RaplaMobileException;

/**
 * Facade Factory (Singleton)
 * 
 * @author Maximilian Lenkeit <dev@lenki.com>
 * @version 1.0
 */
public class FacadeFactory {

	private static FacadeFactory instance;

	private FacadeFactory() {

	}

	/**
	 * Get facade factory instance (singleton)
	 * 
	 * @return FacadeFactory
	 */
	public static FacadeFactory getInstance() {
		if (instance == null) {
			instance = new FacadeFactory();
		}
		return instance;
	}

	/**
	 * Create ClientFacade instance
	 * 
	 * @param url
	 *            Url for rapla server
	 * @param port
	 *            Port for rapla server
	 */
	public ClientFacade createInstance(String url, int port)
			throws RaplaMobileException {
		ConsoleLogger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);

		try {
			StartupEnvironment env = new RaplaConnectorStartupEnvironment(url,
					port, "/", false, logger);
			RaplaMainContainer container = new RaplaMainContainer(env);
			RaplaContext context = container.getContext();
			ClientFacade facade = (ClientFacade) context
					.lookup(ClientFacade.ROLE);
			return facade;
		} catch (Exception ex) {
			throw new RaplaMobileException("Starting up client facade failed",
					ex);
		}
	}
}
